<template>
  <wd-popup position="bottom" v-model="show">
    <PageLayout
      :navTitle="navTitle"
      type="popup"
      navRightText="确定"
      @navRight="handleConfirm"
      @navBack="handleCancel"
    >
      <view class="wrap">
        <z-paging
          ref="paging"
          :fixed="false"
          v-model="dataList"
          @query="queryList"
          :default-page-size="15"
        >
          <template #top>
            <wd-search
              hide-cancel
              :placeholder="searchPlaceholder || `请输入${textField}搜索`"
              v-model="searchKeyword"
              @search="handleSearch"
              @clear="handleClear"
            />
          </template>

          <template v-if="multi">
            <wd-checkbox-group shape="square" v-model="checkedValue">
              <template v-for="(item, index) in dataList" :key="index">
                <view class="list" @click="hanldeCheck(index)">
                  <view class="left text-gray-5">
                    <template v-for="(column, cIndex) in displayColumns" :key="cIndex">
                      <view class="row">
                        <text class="label">{{ column.label }}：</text>
                        <text class="value">{{ item[column.prop] }}</text>
                      </view>
                    </template>
                  </view>
                  <view class="right" @click.stop>
                    <wd-checkbox ref="checkboxRef" :modelValue="index"></wd-checkbox>
                  </view>
                </view>
              </template>
            </wd-checkbox-group>
          </template>

          <template v-else>
            <wd-radio-group shape="dot" v-model="checkedValue">
              <template v-for="(item, index) in dataList" :key="index">
                <wd-cell>
                  <view class="list" @click="hanldeCheck(index)">
                    <view class="left text-gray-5">
                      <template v-for="(column, cIndex) in displayColumns" :key="cIndex">
                        <view class="row">
                          <text class="label">{{ column.label }}：</text>
                          <text class="value">{{ item[column.prop] }}</text>
                        </view>
                      </template>
                    </view>
                    <view class="right" @click.stop>
                      <wd-radio :value="index"></wd-radio>
                    </view>
                  </view>
                </wd-cell>
              </template>
            </wd-radio-group>
          </template>
        </z-paging>
      </view>
    </PageLayout>
  </wd-popup>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useToast } from 'wot-design-uni'
import { http } from '@/utils/http'
import { debounce } from 'lodash-es'

const props = defineProps({
  api: {
    type: Object,
    required: true,
    validator(value) {
      return (
        value.url &&
        typeof value.url === 'string' &&
        value.method &&
        typeof value.method === 'string'
      )
    },
  },
  columns: {
    type: Array,
    required: true,
  },
  keywordField: {
    type: String,
    default: 'keyWord',
  },
  textField: {
    type: String,
    required: true,
  },
  valueField: {
    type: String,
    required: true,
  },
  multi: {
    type: Boolean,
    default: false,
  },
  searchPlaceholder: {
    type: String,
    default: '',
  },
})

const emit = defineEmits(['change', 'close'])

const toast = useToast()
const show = ref(true)
const paging = ref(null)
const dataList = ref([])
const checkedValue = ref(props.multi ? [] : '')
const checkboxRef = ref(null)
const searchKeyword = ref('')
const navTitle = ref('选择')

// 显示列（至少包含textField和valueField）
const displayColumns = computed(() => {
  const requiredFields = [props.textField, props.valueField]
  return props.columns
    .filter(
      (col) =>
        requiredFields.includes(col.prop) ||
        (col.show !== false && !requiredFields.includes(col.prop)),
    )
    .slice(0, 3) // 最多显示3列
})

const handleClose = () => {
  setTimeout(() => {
    emit('close')
  }, 400)
}

const handleConfirm = () => {
  if (props.multi && checkedValue.value.length === 0) {
    toast.warning('请至少选择一项')
    return
  }
  if (!props.multi && checkedValue.value === '') {
    toast.warning('请选择一项')
    return
  }

  const result = []
  const selectedIndexes = props.multi ? checkedValue.value : [checkedValue.value]

  selectedIndexes.forEach((index) => {
    if (dataList.value[index]) {
      result.push(dataList.value[index])
    }
  })

  show.value = false
  emit('change', result)
  handleClose()
}

const handleCancel = () => {
  show.value = false
  handleClose()
}

// 搜索处理（带防抖）
const handleSearch = debounce(() => {
  paging.value.reload()
}, 500)

// 清除搜索条件
const handleClear = () => {
  searchKeyword.value = ''
  handleSearch()
}

const hanldeCheck = (index) => {
  if (props.multi) {
    if (Array.isArray(checkboxRef.value)) {
      checkboxRef.value[index].toggle()
    }
  } else {
    checkedValue.value = index
  }
}

const queryList = async (pageNo, pageSize) => {
  try {
    const params = {
      pageNo,
      pageSize,
      [props.keywordField]: searchKeyword.value,
    }

    let requestFn
    const method = props.api.method.toUpperCase()

    switch (method) {
      case 'GET':
        requestFn = http.get
        break
      case 'POST':
        requestFn = http.post
        break
      case 'PUT':
        requestFn = http.put
        break
      case 'DELETE':
        requestFn = http.delete
        break
      default:
        requestFn = http.get
    }

    const res = await requestFn(
      props.api.url,
      method === 'GET' ? params : undefined,
      method !== 'GET' ? params : undefined,
    )

    if (res.success) {
      const data = res.data || res.result
      paging.value.complete(data.records || [])
    } else {
      toast.error(res.message || '请求失败')
      paging.value.complete(false)
    }
  } catch (error) {
    console.error(error)
    toast.error('请求异常')
    paging.value.complete(false)
  }
}
</script>

<style lang="scss" scoped>
/* 原有样式保持不变 */
</style>
